package com.ln.store.dao.Impl;

import java.sql.SQLException;
import java.util.List;
import java.util.logging.Handler;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.ln.store.dao.ProductDao;
import com.ln.store.domain.Product;
import com.ln.store.utils.JDBCUtils;

public class ProductImpl implements ProductDao {


	public List<Product> findNews() throws SQLException {
		
		String sql = "select * from product where pflag=0 order by pdate DESC limit 0,9 ";
		QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
		return runner.query(sql, new BeanListHandler<Product>(Product.class));
	}

	public List<Product> findHots() throws SQLException {
		
		String sql = "select * from product where pflag=0 and is_hot=1 order by pdate DESC limit 0,9";
		QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
		return runner.query(sql, new BeanListHandler<Product>(Product.class));
	}

	public Product findProductByPid(String pid) throws SQLException {
		String sql = "select * from product where pid=?";
		QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
		return runner.query(sql, new BeanHandler<Product>(Product.class),pid);
	}

	public int findTotalRecord(String cid) throws SQLException {
		String sql = "select count(*) from product where cid=?";
		QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
		Long result = (Long) runner.query(sql, new ScalarHandler(),cid);
		return result.intValue();
	}

	public List<Product> findProductsByCidWithPage(String cid, int startIndex,int PageSize) throws SQLException {
		String sql = "select * from product where cid=?  limit ?,?";
		QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
		return runner.query(sql, new BeanListHandler<Product>(Product.class),cid,startIndex,PageSize);
	}

}
